package com.example.movie_demo

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import kotlinx.android.synthetic.main.fragment_music_play.*
import java.util.concurrent.TimeUnit

class MusicPlayFragment : Fragment() {

    private val notifyId: Int = 0x11
    private val channelId: String = "music Play"

    private lateinit var con: MyConnection

    private lateinit var data: Data

    var mediaPlayer: MediaPlayer? = null


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_music_play, container, false)
    }

    @SuppressLint("SetTextI18n")
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        arguments?.get("data").let {
            this.data = it as Data
        }

        val service = Intent(requireContext(), MusicService::class.java)

        con = MyConnection()
        requireContext().startService(service)
        requireContext().bindService(service, con, Context.BIND_AUTO_CREATE)

        play.setOnClickListener {
            if (play.text.toString() == "PLAY") {
                play.text = "PAUSE"
                con.musicServiceBinder.resume()
                EventUtil.appendEvent("resume Music")

            } else {
                play.text = "PLAY"
                con.musicServiceBinder.pause()
                EventUtil.appendEvent("pause Music")
            }

        }

        restart.setOnClickListener {
            play.text = "PAUSE"
            con.musicServiceBinder.restart(data.bgMusicIndex)
            EventUtil.appendEvent("restart Music")
        }

        when (data.bgMusicIndex) {
            0 -> {
                mediaPlayer = MediaPlayer.create(requireContext(), R.raw.gotechgo)
                bgImage.setImageResource(R.drawable.gotego)
            }
            1 -> {
                mediaPlayer = MediaPlayer.create(requireContext(), R.raw.mario)
                bgImage.setImageResource(R.drawable.enter_sandman_in)
            }
            2 -> {
                mediaPlayer = MediaPlayer.create(requireContext(), R.raw.tetris)
                bgImage.setImageResource(R.drawable.tech_triumph)
            }
        }

    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun sendNotification() {
        //发送登录成功通知
        val notificationManager =
            requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val notificationChannel =
            NotificationChannel(channelId, "chanel", NotificationManager.IMPORTANCE_HIGH)
        //设置通知属性
        notificationChannel.enableVibration(true)
        notificationChannel.enableLights(true)
//        notificationChannel.setSound(Settings.System.getUriFor("global"),Notification.AUDIO_ATTRIBUTES_DEFAULT)
        notificationManager.createNotificationChannel(notificationChannel);

        val notification = Notification.Builder(requireContext(), channelId)
        //设置通知打开后自动消失
        notification.setAutoCancel(true)
        notification.setSmallIcon(R.drawable.ic_launcher_foreground)
        notification.setContentTitle("musci playing!")
        notification.setContentText("click me to edit View!")
        notification.setWhen(System.currentTimeMillis())

        val notificationIntent = Intent(requireContext(), MainActivity::class.java)
        //使用这个PendingIntent的目的是当点击的时候再初始化那个要显示的activity
        val pi = PendingIntent.getActivity(requireContext(), 0x11, notificationIntent, 0)
        notification.setContentIntent(pi)

        //发送通知
        notificationManager.notify(notifyId, notification.build())
    }


    inner class MyConnection : ServiceConnection {

        lateinit var musicServiceBinder: MusicService.MyBinder


        @RequiresApi(Build.VERSION_CODES.O)
        override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
            binder as MusicService.MyBinder
            this.musicServiceBinder = binder
            Log.e("dev", "onServiceConnected: $data")
            binder.getService().setOnLoadCompleteListener(object : OnLoadCompleteListener {
                override fun complete() {
                    playMusics(binder)
                }

            })

            if (binder.getService().loadFinished) {
                playMusics(binder)
            }

            sendNotification()
        }

        private fun playMusics(binder: MusicService.MyBinder) {
            binder.playBgMusic(data.bgMusicIndex)

            Log.e("TAG", "playMusics: ${mediaPlayer!!.duration}")

            val duration = mediaPlayer!!.duration


            val delay = getDelay(duration, data.edffectMusic1Progress)
            ThreadUtil.INSTANCE.schedule({
                binder.playEffectMusic(data.edffectMusic1Index)
            }, delay, TimeUnit.MILLISECONDS)

            ThreadUtil.INSTANCE.schedule({
                binder.playEffectMusic(data.edffectMusic2Index)
            }, getDelay(duration, data.edffectMusic2Progress), TimeUnit.MILLISECONDS)

            ThreadUtil.INSTANCE.schedule({
                binder.playEffectMusic(data.edffectMusic3Index)
            }, getDelay(duration, data.edffectMusic3Progress), TimeUnit.MILLISECONDS)

        }

        private fun getDelay(duration: Int, progress: Int): Long {
            val delay = ((progress * 1.0 / 100) * duration).toLong()
            return delay
        }

        override fun onServiceDisconnected(name: ComponentName?) {

        }

    }

}